<template>
  <div class="sty">
    <!-- 下拉刷新 -->
    <van-pull-refresh v-model="isLoading" @refresh="onRefresh" v-if='shopCarData.length!==0'>
      <van-swipe-cell v-for="item in shopCarData" :key="item.id">
        <!-- 商品卡片 -->
        <van-card :num="item.count" :price="item.sell_price + '.00'" :title="item.title" :thumb="item.thumb_path">
          <div slot="footer">
            <!-- 步进器 -->
            <van-stepper v-model="item.count" min="1" max="9" integer @plus="setAdd(item.id)" @minus="setRed(item.id)"/>
          </div>
        </van-card>
        <!-- 左滑删除按钮 -->
        <van-button slot="right" square text="删除" type="danger" class="delete-button" @click="dels(item.id)"/>
      </van-swipe-cell>
    </van-pull-refresh>

    <!-- 购物车为空时的样式 -->
    <div v-else class="empty">
        <p>购物车空空如也</p>
        <van-button plain type="warning" to="/goods/list" size="mini">去逛逛</van-button>
    </div>

    <!-- 提交订单栏 -->
    <van-submit-bar :price="totalValue*100" button-text="提交订单" @submit="onSubmit" />
  </div>
</template>
<script>
import { mapState, mapMutations, mapGetters } from 'vuex'
export default {
  created () {
    this.getShopcarList()
  },
  data () {
    return {
      // 购物车数据列表
      shopcarList: [],
      // 下拉刷新
      isLoading: false
    }
  },
  methods: {
    ...mapMutations(['merge', 'setAdd', 'setRed', 'del']),
    // 获取购物车列表数据
    async getShopcarList () {
      // 将本地存储的id保存到数组中
      const id = this.shopCarData.map(item => {
        return item.goodsId
      })
      // console.log(id)
      // 发送请求
      const { data: res } = await this.$axios.get(`/api/goods/getshopcarlist/${id}`)
      // console.log(res.message)
      this.shopcarList = res.message
      // 将购物车列表数据和vuex的商品信息进行合并
      this.merge(this.shopcarList)
    },
    // 下拉刷新触发的事件
    onRefresh () {
      setTimeout(() => {
        this.getShopcarList()
        this.isLoading = false
        this.$toast('刷新成功')
      }, 500)
    },
    // 点击提交订单触发的事件
    onSubmit () {
      this.$toast.fail('有钱吗你')
    },
    // 删除商品
    dels (id) {
      this.del(id)
      this.$toast.success('删除商品成功')
    }
  },
  computed: {
    ...mapState(['shopCarData']),
    ...mapGetters(['totalValue'])
  }
}
</script>

<style scoped lang="less">
.sty{
  padding: 4px 0;
}
.van-card{
  margin: 10px 0;
}
.van-pull-refresh{
  min-height: 250px;
  padding-bottom: 50px;
}
.van-image{
  min-height: 0;
  padding: 0;
}
.delete-button {
  height: 100%;
}
.van-card__price{
  font-size: 16px;
}
.empty{
  color: #ccc;
  padding: 15px 0;
  text-align: center;
  p{
    margin: 16px 0;
  }
}
</style>
